﻿using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace WebApplication1
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            Random random = new Random();
            context.Response.ContentType = "text/plain";
            //context.Response.ContentType = "image/jpeg";
            //创建一个位图
            Bitmap bitmap = new Bitmap(60, 30);
            //根据新建的位图，创建一个画布
            //注意：这里Graphics类没有提供构造函数，所以不能直接建立Graphics类的对象
            Graphics g = Graphics.FromImage(bitmap);
            //设置画布背景颜色为白色
            g.Clear(Color.White);
            //设置边框
            g.DrawRectangle(new Pen(Color.Black), 0, 0, bitmap.Width - 1, bitmap.Height - 1);
            //设置干扰点(噪音点)
            for (int i = 0; i < 70; i++)
            {
                int x = random.Next(bitmap.Width);
                int y = random.Next(bitmap.Height);
                bitmap.SetPixel(x, y, Color.Brown);
            }
            //设置干扰线（噪音线）
            for (int i = 0; i < 6; i++) //这里的噪音线数量不能太多，否则难以看清
            {
                int x1 = random.Next(bitmap.Width);
                int y1 = random.Next(bitmap.Height);//线的起点
                int x2 = random.Next(bitmap.Width);
                int y2 = random.Next(bitmap.Height);//线的终点
                g.DrawLine(new Pen(Color.Green), x1, y1, x2, y2);

            }
            //3.设置画图内容
            string s = "0123456789abcdefghjklmnopqrstuvwxyz"; //注：由于数字0和字母O不好辨认，所以可以选择去掉它们
            string vcode = "";
            for (int i = 0; i < 4; i++) //一般验证码长度为4个字符，可根据需要自定义
            {
                int index = random.Next(s.Length);
                vcode += s[index];
            }
            context.Session["vcode"] = vcode;

            //4.画图
            //设置符号渐变效果
            LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, bitmap.Width, bitmap.Height), Color.Black, Color.Red, 1.2f);
            g.DrawString(vcode, new Font("宋体", 18), brush, 0, 0);

            //5.保存
            //第一种方式:不建议使用
            //string path=context.Request.MapPath("img");
            //bitmap.Save(path + "/" + vcode + ".jpg");
            //context.Response.Write("图片生产成功！");
            //第二种方式:
            bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}